import {
    ref,
    onMounted,
    onUnmounted,
    computed
} from 'vue'

import {
    filter
} from '../util/todoStorage'

// 有效的hash数组
const validHash = ['all', 'active', 'completed']

export default function useFilters(todoRef) {
    // 默认显示全部
    const visibilityRef = ref('all')

    const onHashChange = () => {
        console.log('hash的值变化了')
        const hash = location.hash.replace(/#\/?/, '')

        if (validHash.includes(hash)) {
            //有效的hash值  
            visibilityRef.value = hash
        } else {

            location.hash = ''
            visibilityRef.value = 'all'
        }
    }

    // 1.组件挂载完成的生命周期函数
    onMounted(() => {
        console.log('onMounted')
        window.addEventListener('hashchange', onHashChange)
    })
    // 2.组件销毁过后的生命周期函数
    onUnmounted(() => {
        console.log('onUnmounted')
        window.removeEventListener('hashchange', onHashChange)
    })

    // 计算属性(筛选方式，得到任务列表)
    const filterTodoRef = computed(() => {
        return filter(todoRef.value, visibilityRef.value)
    })

    // 还有任务未完成的个数
    const remainTodoRef = computed(() => {
        return filter(todoRef.value, 'active').length
    }) 
    
    
    // 还有任务完成的个数
    const completeTodoRef = computed(() => {
        return filter(todoRef.value, 'completed').length
    })

    return {
        visibilityRef,
        filterTodoRef,
        remainTodoRef,
        completeTodoRef
    }
}